import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CustomUiPage extends StatelessWidget {
  const CustomUiPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // ignore: unused_local_variable
    final MethodChannel channel = MethodChannel(
      'com.example/custom_channel',
      const StandardMethodCodec(),
    );
    final Map<String, dynamic> creationParams = <String, dynamic>{
      "text": "iOS Label"
    };
    MethodChannel viewChannel =
        const MethodChannel('com.example/custom_channel_view');

    void onPlatformViewCreated(int id) {
      print('This is onPlatformViewCreated');
      // ignore: missing_return
      viewChannel.setMethodCallHandler((MethodCall call) {
        // 处理MethodCall，如果需要的话
        print('xxxxxx setMethodCallHandler xxxxxx');
        if (call.method == "sendMessageFromPlatform") {
          print("call.arguments, ${call.arguments}");
        }
      });
    }

    Widget uiCustomWidget = Platform.isAndroid
        ? AndroidView(
            viewType: 'com.example/custom_view',
            creationParams: {
              "myContent": "AndroidView",
            },
            creationParamsCodec: StandardMessageCodec(),
            onPlatformViewCreated: onPlatformViewCreated,
          )
        : UiKitView(
            viewType: 'com.example/custom_view',
            creationParams: creationParams,
            creationParamsCodec: StandardMessageCodec(),
            onPlatformViewCreated: onPlatformViewCreated,
          );

    return Scaffold(
      appBar: AppBar(
        title: Text('CustomUiPage'),
      ),
      body: Container(
        child: Column(
          children: [
            Container(
              height: 320.0,
              child: Padding(
                child: uiCustomWidget,
                padding: EdgeInsets.all(16.0),
              ),
            ),
            Center(
              child: TextButton(
                onPressed: () {
                  viewChannel.invokeMethod(
                    'setPlatformView',
                    {'url': 'https://pub.dev'},
                  );
                  // channel.invokeMethod('getPlatform', {"badgeCount": 2});
                },
                child: Text('MethodChannel'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
